# -*- coding: utf-8 -*-
"""
日志模块
"""

import os
import datetime
import sys

# 安全的打印函数
def safe_print(msg):
    """安全的打印函数，处理 stderr/stdout 为 None 的情况"""
    try:
        if sys.stdout and not sys.stdout.closed:
            print(msg)
    except:
        pass

def log(msg):
    """统一的日志函数"""
    try:
        txt = f"[DEBUG] {datetime.datetime.now():%m-%d %H:%M:%S}  {msg}"
        safe_print(txt)  # 使用安全的打印
        
        # 动态获取数据目录
        log_file = _get_log_file_path()
        with open(log_file, 'a', encoding='utf-8') as f:
            f.write(txt + '\n')
    except Exception as e:
        # 如果日志写入失败，至少尝试安全打印
        safe_print(f"[LOGGER-ERROR] {e}")

def _get_log_file_path():
    """动态获取日志文件路径"""
    try:
        # 尝试从环境变量或默认路径获取
        data_dir = os.environ.get('TRACKER_DATA_DIR')
        if data_dir and os.path.exists(data_dir):
            return os.path.join(data_dir, 'runtime.log')
        
        # 尝试常见的可能路径
        possible_paths = [
            'D:\\Tracker_Data',
            'D:\\python_Data', 
            os.path.join(os.path.expanduser('~'), 'Tracker_Data'),
            os.path.dirname(os.path.abspath(__file__))  # 当前目录
        ]
        
        for path in possible_paths:
            if os.path.exists(path):
                return os.path.join(path, 'runtime.log')
        
        # 如果都找不到，使用当前目录
        return 'runtime.log'
        
    except Exception:
        # 兜底方案
        return 'runtime.log'